package com.yingeo.pos.mobile;

import android.app.Application;
import android.text.TextUtils;

import com.baidu.mapapi.SDKInitializer;

import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;

/**
 * @名称 FlutterMethodChannel
 * @描述 Android原生和Flutter通信通道
 * @时间 2022/03/01 5:13 PM
 */
public class FlutterMethodChannel {

    private Application application;

    private static final String TAG = "FlutterMethodChannel";

    private static String CHANNEL = "FlutterNativeChannel";
    private MethodChannel methodChannel;

    private static volatile FlutterMethodChannel singleton = null;

    private FlutterMethodChannel() {}

    public static FlutterMethodChannel getInstance() {
        if (singleton == null) {
            synchronized (FlutterMethodChannel.class) {
                if (singleton == null) {
                    singleton = new FlutterMethodChannel();
                }
            }
        }
        return singleton;
    }

    /**
     * 初始化
     * @param flutterEngine
     */
    public void registerWith(FlutterEngine flutterEngine, Application application) {
        this.application = application;
        methodChannel = new MethodChannel(flutterEngine.getDartExecutor(), CHANNEL);
        methodChannel.setMethodCallHandler((call, result) -> {
            System.out.println("MethodCallHandler:::CallBack : " + call.method);
            receivedFromFlutter(call, result);
        });
    }

    /**
     * 发送数据到flutter
     * @param method
     * @param data
     */
    public void push2Flutter(String method, String data) {
        methodChannel.invokeMethod(method, data);
    }

    /**
     * 接收到来自flutter的数据
     * @param call
     * @param result
     */
    private void receivedFromFlutter(MethodCall call, MethodChannel.Result result) {
        if (call == null) {
            return;
        }
        String method = call.method;
        if (TextUtils.isEmpty(method)) {
            return;
        }
        if (method.equals("initBaiduMapSDK")) {
            initBaiduMapSDK(result);
        } else if (method.equals("initTextToSpeechSdk")) {
            initTextToSpeechSdk();
        } else if (method.equals("startTextToSpeech")) {
            startTextToSpeech(call.argument("message"));
        } else {
            result.notImplemented();
        }
    }

    /**
     * 百度地图SDK初始化
     */
    private void initBaiduMapSDK(MethodChannel.Result result) {
        SDKInitializer.initialize(application);
        result.success(null);
    }

    /**
     * 初始化语音播报SDK
     */
    private void initTextToSpeechSdk() {
        XunFeiTtsHandler.getInstance().initSdk(application.getApplicationContext());
    }

    /**
     * 语音播报
     */
    private void startTextToSpeech(String message) {
        XunFeiTtsHandler.getInstance().startSpeak(message);
    }

}
